package top.aylan.org.ctrl.admin;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
import top.aylan.org.Common.SystemConstants;
import top.aylan.org.entity.Options;
import top.aylan.org.service.OptionsService;
import top.aylan.org.tools.Directory;
import top.aylan.org.tools.FileUploader;
import top.aylan.org.tools.Result;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by Administrator on 2018/12/9.
 */
@Controller
@RequestMapping("/admin")
public class AdminIndexController {

    @Resource
    OptionsService optionsService;

    @RequestMapping(value ={"","/","/index","/index.html"})
    public String index(){

        return "admin/index";
    }


    @RequestMapping(value = "/settings")
    public String settings(ModelMap modelMap){

        try {
            List<Options> options = optionsService.findAllOptions();
            modelMap.addAttribute("options",options);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "admin/settings";
    }

    @RequestMapping(value="/settings/save",method = RequestMethod.POST)
    public String updateSttings(
            @RequestParam(value = "webName",defaultValue = "") String webName,
            @RequestParam(value = "introduce",defaultValue = "") String introduce,
            HttpServletRequest request,
            MultipartFile file
    ){

        Options nameOpt = new Options();
        nameOpt.setOptionName("web_name");
        nameOpt.setOptionValue(webName);
        nameOpt.setId((byte)1);

        Options introOpt = new Options();
        introOpt.setOptionName("web_introduce");
        introOpt.setOptionValue(introduce);
        introOpt.setId((byte)4);

        try {
            optionsService.update(nameOpt);
            optionsService.update(introOpt);

        } catch (Exception e) {
            e.printStackTrace();
        }

        FileUploader fileUploader = new FileUploader();
        Result result = fileUploader.upload(file, Directory.SYSTEM);
        if(result.getCode() == 1){
            Options logoOpt = new Options();
            logoOpt.setOptionName("web_logo");
            logoOpt.setOptionValue((String) result.getData().get("path"));
            logoOpt.setId((byte)3);
            optionsService.update(logoOpt);
        }else if(result.getCode() == -1){
            System.out.println(result.getMessage());
        }
        return "redirect:/admin/settings";
    }
}
